package com.fusheng.demo.accessibilityservice

import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.content.Intent.FLAG_ACTIVITY_NEW_TASK
import android.util.Log
import android.view.View
import android.view.ViewGroup
import android.view.accessibility.AccessibilityNodeInfo
import com.fusheng.demo.accessibilityservice.WeChatMotionMonitor.isContainChinese
import java.lang.Exception
import java.util.regex.Pattern

object WeChatMotionMonitor {

    var step = 0

    //正确轨道
    var isProperPath = false
    var isPathComplete = false

    //确定相册加载完成
    var isLoadAlbumPreviewUI = false

    var step6Time = 0L

    /**
     * 朋友圈页面
     */
    private const val CLASS_NAME_FRIENDS = "com.tencent.mm.plugin.sns.ui.SnsTimeLineUI"

    /**
     * 微信相册
     */
    private const val CLASS_NAME_ALBUMUI = "com.tencent.mm.plugin.gallery.ui.AlbumPreviewUI"


    /**
     * 每一个对应的点位ID ，不同微信版本ID有差异
     */
    private var clickIds = HashMap<String, List<String>>().apply {
        put("back", listOf("com.tencent.mm:id/g0", "com.tencent.mm:id/fz")) //
        put("found", listOf("com.tencent.mm:id/kd_", "com.tencent.mm:id/kdk"))
        put("friends", listOf("com.tencent.mm:id/iwg", "com.tencent.mm:id/iwp"))
        put("albumPop", listOf("com.tencent.mm:id/eo", "com.tencent.mm:id/en"))
        put("albumPopItem", listOf("com.tencent.mm:id/iwc", "com.tencent.mm:id/iwl"))
        put("albumSelect", listOf("com.tencent.mm:id/gpy", "com.tencent.mm:id/gq5"))
        put("albumNext", listOf("com.tencent.mm:id/en", "com.tencent.mm:id/em"))
        put("editTxt", listOf("com.tencent.mm:id/jsy", "com.tencent.mm:id/jt9"))
    }

    /**
     * 启动微信界面
     * adb shell am start com.tencent.mm/com.tencent.mm.ui.LauncherUI
     */
    fun startWechat(mContext: Context) {
        val intent = Intent()
        intent.setPackage("com.tencent.mm")
        intent.setClassName(
            "com.tencent.mm",
            "com.tencent.mm.ui.LauncherUI"
        )
        intent.flags = FLAG_ACTIVITY_NEW_TASK
        mContext.startActivity(intent)

        //初始化
        step = 0
        isProperPath = false
        isPathComplete = false
        isLoadAlbumPreviewUI = false
    }

    /**
     * 启动支付宝界面
     * adb shell am start com.eg.android.AlipayGphone/com.eg.android.AlipayGphone.AlipayLogin
     */
    fun returnStartApp(mContext: Context) {
        val intent = Intent()
        intent.setPackage("com.fusheng.demo")
        intent.setClassName(
            "com.fusheng.demo",
            "com.fusheng.demo.MainActivity"
        )
        intent.flags = FLAG_ACTIVITY_NEW_TASK
        mContext.startActivity(intent)
    }

    fun policy(
        nodeInfo: AccessibilityNodeInfo?,
        packageName: String?,
        className: String?,
        context: Context
    ) {
        if (nodeInfo == null || className == null || isPathComplete) {
            return
        }
        if ("com.tencent.mm" != packageName) {
            return
        }

        //朋友圈页面  className=com.tencent.mm.plugin.sns.ui.SnsTimeLineUI
        //发表页面  className=com.tencent.mm.plugin.sns.ui.SnsUploadUI
        //个人信息页面 className=com.tencent.mm.plugin.profile.ui.ContactInfoUI  com.tencent.mm:id/g0

        //将无障碍移动到固定轨道上
        if (className.startsWith("com.tencent.mm")) {

            if (!isProperPath) {
                //默认在朋友圈页面
                if (CLASS_NAME_FRIENDS == className) {
                    step = 2
                    isProperPath = true
                } else if ("com.tencent.mm.plugin.sns.ui.SnsUploadUI" == className) {

                } else if ("com.tencent.mm.ui.LauncherUI" == className) {
                    //好友列表页面纠正
                    var listNode = nodeInfo.findAccessibilityNodeInfosByText("发现")
                    if (listNode.size == 0) {
//                        performClick(nodeInfo, "com.tencent.mm:id/g0")
                        performClick(nodeInfo, clickIds["back"]!!)
//                        Log.e("AutoShareWXService", "======模拟调试页面 ${listNode.size}======")
                        step = 0
                        Thread.sleep(400)
                    }
                } else {
                    //非聊天二级页面，退出到首页面
                    //com.tencent.mm:id/fz
//                    performClick(nodeInfo, "com.tencent.mm:id/g0")
                    performClick(nodeInfo, clickIds["back"]!!)
                    step = 0
                }
            }
        }

        // 该界面下所有 ViewId 节点
        if (step == 0) {
            var listNode = nodeInfo.findAccessibilityNodeInfosByText("发现")
            if (listNode.size > 0) {
//                Log.e("AutoShareWXService", "====== 0 选中发现======")
//                performClick(nodeInfo, "com.tencent.mm:id/kd_", 2, 4)
//                performClick(nodeInfo, "com.tencent.mm:id/kdk", 2, 4)
                performClick(nodeInfo, clickIds["found"]!!, 2, 4)
            }
        } else if (step == 1) {
            // 模拟微信>发现>朋友圈
//            Log.e("AutoShareWXService", "====== 1 进入朋友圈======")
            isProperPath = true
//            performClick(nodeInfo, "com.tencent.mm:id/iwg")
//            performClick(nodeInfo, "com.tencent.mm:id/iwp")
            performClick(nodeInfo, clickIds["friends"]!!)
        } else if (step == 2 && CLASS_NAME_FRIENDS == className) {
            //模拟微信>发现>朋友圈>弹窗相册
//            performClick(nodeInfo, "com.tencent.mm:id/eo")
            // 拍照分享
//            performClick(nodeInfo, "com.tencent.mm:id/en")
            performClick(nodeInfo, clickIds["albumPop"]!!)
        } else if (step == 3) {
            //从相册选择
//            performClick(nodeInfo, "com.tencent.mm:id/iwc", 1)
//            performClick(nodeInfo, "com.tencent.mm:id/iwl", 1)
            performClick(nodeInfo, clickIds["albumPopItem"]!!, 1)
        } else if (step == 4) {
            //从相册选择 ->  选中多少张
            // 初始 可能相册加载慢一拍，到账check 不可选
            if (CLASS_NAME_ALBUMUI == className) {
                isLoadAlbumPreviewUI = true
            }

            if (isLoadAlbumPreviewUI) {
//                val list = nodeInfo.findAccessibilityNodeInfosByViewId("com.tencent.mm:id/gpy")
//                val list = nodeInfo.findAccessibilityNodeInfosByViewId("com.tencent.mm:id/gq5")
//                put("albumSelect", listOf("com.tencent.mm:id/gpy", "com.tencent.mm:id/gq5"))
//                Log.e("AutoShareWXService", "====== 4 选中多张图片 ${list.size}======")
                outLabel@ for (id in clickIds["albumSelect"]!!.indices) {
                    val list =
                        nodeInfo.findAccessibilityNodeInfosByViewId(clickIds["albumSelect"]!![id])
                    val maxSelect = 9
                    for (i in list.indices) {
//                    Log.e(
//                        "AutoShareWXService",
//                        "${list[0].className}====== index= $i click ${list[i].isClickable}= check ${list[i].isCheckable}====="
//                    )
                        if (list[i].isClickable) {
                            if (i >= maxSelect) {
                                step++
                                break@outLabel
                            }
                            list[i].performAction(AccessibilityNodeInfo.ACTION_CLICK)
                        } else {
                            //异常不可选直接推车循环
                            break
                        }
                    }
                }

                //修复异常情况步骤 05
                if (CLASS_NAME_ALBUMUI != className && step == 5) {
                    //图片选择完成
//                    performClick(nodeInfo, "com.tencent.mm:id/en")
//                    performClick(nodeInfo, "com.tencent.mm:id/em")
                    performClick(nodeInfo, clickIds["albumNext"]!!)
                }
            }
        } else if (step == 5) {
            //图片选择完成
//            performClick(nodeInfo, "com.tencent.mm:id/en")
//            performClick(nodeInfo, "com.tencent.mm:id/em")
            performClick(nodeInfo, clickIds["albumNext"]!!)

        } else if (step == 6) {
            //文字填充
            // 这一刻的想法...
//            setTextFromClipboard(nodeInfo, "com.tencent.mm:id/jsy", context)
//            setTextFromClipboard(nodeInfo, "com.tencent.mm:id/jt9", context)
            setTextFromClipboard(nodeInfo, clickIds["editTxt"]!!, context)
            step6Time = System.currentTimeMillis()
        } else if (step == 7 && CLASS_NAME_FRIENDS == className) {
            //手动发布完成 ，后续操作
            if (System.currentTimeMillis() - step6Time > 400) {
                isPathComplete = true
                returnStartApp(context)
            }
        }

    }

    /**
     * 模拟点击事件
     */
    private fun performClick(
        nodeInfo: AccessibilityNodeInfo,
        viewIds: List<String>,
        index: Int = 0,
        size: Int = 0
    ) {
//        val list = nodeInfo.findAccessibilityNodeInfosByViewId(viewIds)
        outLabel@ for (id in viewIds.indices) {
            val list = nodeInfo.findAccessibilityNodeInfosByViewId(viewIds[id])
            Log.e("AutoShareWXService", "step=$step ,size=${list.size}")
            //过滤不定性列表
            if (size > 0 && list.size < size) continue
            //正常取点
            for (i in list.indices) {
                Log.e("AutoShareWXService", "isClickable=${list[i].isClickable} ,index=$i")
                if (i == index && list[i].isClickable) {
                    list[i].performAction(AccessibilityNodeInfo.ACTION_CLICK)
                    step++
                    break@outLabel
                }
            }
        }
    }


    /* 通过粘贴板输入文字 */
    private fun setTextFromClipboard(
        nodeInfo: AccessibilityNodeInfo,
        viewIds: List<String>,
        context: Context
    ) {
        try {
            outLabel@ for (id in viewIds.indices) {
                val s = viewIds[id]
                val list = nodeInfo.findAccessibilityNodeInfosByViewId(s)
//                    if (s.isContainChinese()) {
//                        nodeInfo.findAccessibilityNodeInfosByViewId(s)
//                    } else {
//                        nodeInfo.findAccessibilityNodeInfosByViewId(s)
//                    }
                for (i in list.indices) {
                    if (list[i].isClickable) {
//                    val clipboard =
//                        context.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
//                    val clip = ClipData.newPlainText("text", "999999999灵灵99");
//                    clipboard.setPrimaryClip(clip);
                        //获得焦点
                        list[i].performAction(AccessibilityNodeInfo.ACTION_FOCUS)
                        //粘贴内容
                        list[i].performAction(AccessibilityNodeInfo.ACTION_PASTE)
                        step++
                        break@outLabel
                    }
                }
            }
        } catch (e: Exception) {
            e.printStackTrace()
            Log.e("AutoShareWXService", e.message.toString())
        }
    }


    // DES: 判断是否包含中文
    private fun String?.isContainChinese(): Boolean {
        this ?: return false
        val mChinesePattern = Pattern.compile("[\u4e00-\u9fa5]")
        return mChinesePattern.matcher(this).find()
    }


    private fun findParentClickView(view: View): View? {
        (view.parent as? ViewGroup)?.apply {
            return findParentClickView@ this
        }
        if (view != null) {
            val pView = view.parent as? ViewGroup

            return pView
        }

        return null
    }


}